--- 山东泽润管段式晨硕表  modbus 协议 dtype=17,注意:addr=动态设置,编号后俩位是16进制
--- 后期可以自定义addr（通信地址），需要网络设置
module(..., package.seeall)
local logtag = "SDZR_CSB"
local dtu, udtu,addr = {}, {},1
function setDtu(_dtu, _udtu)
    dtu, udtu = _dtu, _udtu
    addr = udtu.addr and tonumber(udtu.addr) or 1
    if udtu and tonumber(udtu.dtype) == 17 then sys.taskInit(init) end
end
function _pro(d)
    local _, m_ins,dw_i = pack.unpack(d:sub(6, 7)..d:sub(4, 5)..d:sub(8, 9), ">IH") --流量
    local _1, m_val,dw_v = pack.unpack(d:sub(18, 19)..d:sub(16, 17)..d:sub(20, 21), ">IH") --累计
    if dw_i==0x0b3b then m_ins = m_ins/1000
    elseif dw_i==0x0b3c then m_ins = m_ins/100
    elseif dw_i==0x0b3d then m_ins = m_ins/10
    elseif dw_i==0x0b3f then m_ins = m_ins*10
    end
    if dw_v==0x0c13 then m_val = m_val/1000
    elseif dw_v==0x0c14 then m_val = m_val/100
    elseif dw_v==0x0c15 then m_val = m_val/10
    elseif dw_v==0x0c17 then m_val = m_val*10
    end
    usrdata.update({m_val, m_ins})
    if lcd.LCD_DATA[3]:match('累计(.+)') then
        lcd.LCD_DATA[3] ='流量:' .. (m_ins or "NULL")
        return
    end
    lcd.LCD_DATA[3] ='累计:' .. (m_val or "NULL")
end
function init()
    power.openBoost()
    sys.wait(200)
	while true do
        tools.modbus_send(3,addr,3,0,10)
        local res, d = sys.waitUntil("UART_READ_DONE_NEXT_3" , 5000)
        if res then
            if d then
                _pro(d)
            end
            sys.wait(5000)
        else
            lcd.LCD_DATA[3]="泽润READ TIMEOUT"
        end
	end
end
